package top.atcra.rpc.service;

import cn.hutool.core.lang.Assert;
import io.netty.channel.Channel;
import lombok.Data;
import top.atcra.rpc.RPCBootstrap;
import top.atcra.rpc.proxy.RPCInvocationHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * 服务引用配置，用于客户端生成代理对象
 *
 * @author atcra
 * @date 2025-04-01
 * @param <T> 服务接口类型
 */
@Data
public class ReferenceConfig<T> {
    private String serviceName;
    private String serviceGroup;
    private Class<T> interfaceClass;
    private RPCBootstrap bootstrap;
    private Channel channel;



    public ReferenceConfig(String serviceName, String serviceGroup, Class<T> interfaceClass) {
        this.serviceName = serviceName;
        this.serviceGroup = serviceGroup;
        this.interfaceClass = interfaceClass;
    }
    /**
     *
     * @param bootstrap RPCBootstrap实例
     * @param serviceName 服务名称
     * @param serviceGroup 服务分组
     * @param interfaceClass 服务接口
     */
    public ReferenceConfig(RPCBootstrap bootstrap, String serviceName, String serviceGroup, Class<T> interfaceClass) {
        this.bootstrap = bootstrap;
        this.serviceName = serviceName;
        this.serviceGroup = serviceGroup;
        this.interfaceClass = interfaceClass;
    }

    public T getProxy() {
        Assert.notNull(bootstrap, "bootstrap is null,please call RPCBootstrap.reference() first");
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class<T>[] classes = new Class[]{interfaceClass};
        InvocationHandler handler = new RPCInvocationHandler(serviceName, serviceGroup, bootstrap);

        // 使用动态代理生成代理对象
        Object t = Proxy.newProxyInstance(classLoader, classes, handler);
        return (T) t;
    }
}
